package cpt202.project.controller;
import cpt202.project.entity.Record;
import cpt202.project.service.RecordService;
import cpt202.project.service.exception.DeleteException;
import cpt202.project.service.exception.InsertException;
import cpt202.project.service.exception.ModifyException;
import cpt202.project.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/records")
@RestController
public class RecordController {
    @Autowired
    private RecordService recordService;

    @RequestMapping("/add_new_record")
    //需要返回给用户新添加的record的ID
    public JsonResult<Integer> addNewRecord(Record record){
        JsonResult<Integer> result = new JsonResult<>();
        try{
            Integer newrecID = recordService.add(record);
            result.setState(200); //200代表用户成功添加新的消费记录
            result.setMessage("添加成功");
            result.setData(newrecID);
        }
        catch (InsertException e) {
            result.setState(3000);
            result.setMessage("添加消费记录时发生未知错误");
        }
        return result;
    }

    @RequestMapping("/mod_record")
    public JsonResult<Void> modifyRecord(Record record){
        JsonResult<Void> result = new JsonResult<>();
        try{
            recordService.Modify(record);
            result.setState(200); //200代表用户成功修改消费记录
            result.setMessage("修改成功");
        }
        catch(ModifyException e) {
            result.setState(3010);
            result.setMessage("修改消费记录时发生未知错误");
        }
        return result;
    }

    @RequestMapping("/delete")
    public JsonResult<Void> deleteRecord(Integer recordId){
        JsonResult<Void> result = new JsonResult<>();
        try{
            recordService.delete(recordId);
            result.setState(200); //200代表用户成功删除消费记录
            result.setMessage("删除成功");
        }
        catch (DeleteException e) {
            result.setState(3020);
            result.setMessage("删除消费记录时发生未知错误");
        }
        return result;
    }

}
